<!DOCTYPE html>
<html lang="zh-cn">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>RSA 加密注册</title>
</head>

<body>
<button onclick="register()">注册</button>
<script src="https://cdn.staticfile.net/axios/1.6.5/axios.min.js"></script>
<script src="https://unpkg.com/node-forge@1.3.1/dist/forge.min.js"></script>
<script>
  const storage = {
    set(key, value) {
      localStorage.setItem(key, value);
    },
    get(key) {
      return localStorage.getItem(key);
    },
    remove(key) {
      localStorage.removeItem(key);
    }
  }

  async function getPublicKey() {
    let key = storage.get('ua_publicKay')
    if (!key || key === 'undefined') {
      let result = await axios.get('http://127.0.0.1:3000/api/getPublicKey')
      console.log('result: ', result);
      key = result.data.data.publicKey
      key = key.replace(/\. +/g, '')
      key = key.replace(/[\r\n]/g, '')
      storage.set('ua_publicKay', key)
    }
    return key
  }


  // 添加请求拦截器
  axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });

  function encrypt(publicKey, value) {
    const publicKeyObj = forge.pki.publicKeyFromPem(publicKey);
    const encrypted = publicKeyObj.encrypt(value, 'RSAES-PKCS1-V1_5');
    console.log(forge.util.encode64(encrypted))
    return forge.util.encode64(encrypted);
  }

  function register() {
    getPublicKey().then(key => {
      console.log('key: ', key);
      axios.post('http://127.0.0.1:3000/api/register', {
        username: "aaa1111111",
        password: encrypt(key, 'th123456'),
        email: "3967a22221@qq.com"
      }).then(data => {
        console.log(data)
      })
    })
  }

</script>
</body>

</html>